package com.gmall.auth.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.MD5;
import com.gmall.common.result.Result;
import com.gmall.common.utils.JWTUtils;
import com.gmall.model.auth.LoginForm;
import com.gmall.model.user.UserInfo;
import com.gmall.user.feign.UserApiFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;
    //https://www.jianshu.com/p/3238bb3bcad8

    @Autowired
    UserApiFeignClient userApiFeignClient;

    public final static String CAPTCHA_KEY = "captcha:";
    public final static String TOKEN_KEY = "token:";
    /**
     *
     * @return
     */
    @GetMapping("genCaptcha")
    public Result<Map<String,String>> genCaptcha(){

        CircleCaptcha circleCaptcha =
                CaptchaUtil.createCircleCaptcha(100, 50, 4, 10);
        String code = circleCaptcha.getCode();
        System.out.println("验证码是：" + code);

        String uuid = UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set(CAPTCHA_KEY +uuid,code,30, TimeUnit.SECONDS);//UUID
        String imageBase64 = circleCaptcha.getImageBase64();//图片
        String imageBase64Data = circleCaptcha.getImageBase64Data();//data:image/png;base64,

        Map<String,String> map = new HashMap();
        map.put("uuid",uuid);
        map.put("imageBase64",imageBase64Data);
        return Result.ok(map);
    }

    @PostMapping("login")
    public Result<Map<String,String>> login(@RequestBody LoginForm loginForm){
        //比较验证码是否正确
        Map<String,String> map = new HashMap();
        String uuid = loginForm.getUuid();
        if(!StringUtils.isEmpty(uuid)){
            String codeFromRedis
                    = (String)redisTemplate.opsForValue().get(CAPTCHA_KEY +uuid);
            String codeFromClient = loginForm.getCode();
            if(StringUtils.isEmpty(codeFromRedis)||!codeFromRedis.equalsIgnoreCase(codeFromClient)){
                map.put("message","验证码错误");
                return Result.fail(map);
            }
        }
        //获取该用户信息
        String userName = loginForm.getUserName();
        if(StringUtils.isEmpty(userName)){
            map.put("message","用户名不能为空");
            return Result.fail(map);
        }
        Result<UserInfo> userInfoResult = userApiFeignClient.getUserInfoByLoginName(userName);

        if(userInfoResult!=null && !userInfoResult.isOk()) {
            map.put("message", "用户不存在");
            return Result.fail(map);
        }
        UserInfo userInfo = userInfoResult.getData();
        if(userInfo== null){

            map.put("message", "用户不存在");
            return Result.fail(map);
        }

        String bcrypt_password_fromDB = userInfo.getPasswd();
        String plain_password = loginForm.getPassword();

        //密码加密
        if(!DigestUtil.bcryptCheck(plain_password,bcrypt_password_fromDB))
        {
            map.put("message", "用户不存在或者密码错误");
            return Result.fail(map);
        }

        //比较密码匹配
        String token = JWTUtils.createToken(userInfo.getId().toString(), userInfo.getName());
        redisTemplate.opsForValue().set(TOKEN_KEY + userInfo.getId(),token,5, TimeUnit.MINUTES);

        //生成token
        System.out.println("token = " + token);
        map.put("message","登录成功");
        map.put("token",token);
        map.put("userId",userInfo.getId().toString());
        return Result.ok(map);
    }

    public static void main(String[] args) {
        String passwordPlain = "123456";

        String s1 = MD5.create().digestHex(passwordPlain);
        String s2 = MD5.create().digestHex(passwordPlain);

        String s3 = MD5.create().digestHex(passwordPlain);
        String s4 = MD5.create().digestHex(passwordPlain);


        System.out.println(s1);
        System.out.println(s2);

        String bcrypt2 = DigestUtil.bcrypt(passwordPlain);
        String bcrypt1 = DigestUtil.bcrypt(passwordPlain);
        System.out.println(bcrypt1);
        System.out.println(bcrypt2);

        System.out.println(DigestUtil.bcryptCheck(passwordPlain,bcrypt1));
        System.out.println(DigestUtil.bcryptCheck(passwordPlain,bcrypt2));
    }
}
